"""
状态管理服务层
提供状态相关的业务逻辑处理
"""
import logging
from typing import List, Optional, Dict, Any
from motor.motor_asyncio import AsyncIOMotorDatabase
from bson import ObjectId
from datetime import datetime

from app.models.state import (
    State, StateCreate, StateUpdate, StateResponse, 
    ModuleStateResponse, ModuleType
)
from app.core.state_cache import state_cache

logger = logging.getLogger(__name__)

# 模块类型到集合名称的映射
# 注意：只有使用统一状态管理系统的模块才需要添加到这里
MODULE_COLLECTION_MAP = {
    "requirement": "requirements",
    "task": "tasks",
    "defect": "defects",
    "project": "projects",
    "test_case": "test_cases",
    "test_plan": "test_plans",  # 测试计划模块使用统一状态管理
    "document": "documents",
    "version": "versions",  # 版本模块使用统一状态管理
    # 以下模块类型不使用统一状态管理系统，使用独立的状态字段或不需要状态管理
    # "user": "users",  # 用户状态（激活、禁用）使用独立管理
    # "comment": "comments",  # 评论状态（待审核、已发布）使用独立管理
    # "notification": "notifications",  # 通知状态（未读、已读）使用独立管理
}


class StateService:
    """
    状态管理服务类
    """
    
    @staticmethod
    async def get_states(
        db: AsyncIOMotorDatabase,
        module_type: Optional[ModuleType] = None,
        is_enabled: Optional[bool] = None,
        is_visible: Optional[bool] = None,
        search: Optional[str] = None,
        skip: int = 0,
        limit: int = 100
    ) -> List[StateResponse]:
        """
        获取状态列表
        """
        # 构建查询条件
        query = {}
        
        if module_type:
            query["module_type"] = module_type
        
        if is_enabled is not None:
            query["is_enabled"] = is_enabled
            
        if is_visible is not None:
            query["is_visible"] = is_visible
        
        if search:
            query["$or"] = [
                {"name": {"$regex": search, "$options": "i"}},
                {"code": {"$regex": search, "$options": "i"}},
                {"description": {"$regex": search, "$options": "i"}}
            ]
        
        # 查询数据
        cursor = db.states.find(query).sort("sort_order", 1).skip(skip).limit(limit)
        states = await cursor.to_list(length=limit)
        
        # 转换响应格式
        state_list = [
            StateResponse(
                id=str(state["_id"]),
                name=state["name"],
                code=state["code"],
                module_type=state["module_type"],
                description=state.get("description"),
                color=state.get("color", "#1890ff"),
                icon=state.get("icon"),
                sort_order=state.get("sort_order", 0),
                is_enabled=state.get("is_enabled", True),
                is_visible=state.get("is_visible", True),
                is_default=state.get("is_default", False),
                created_at=state.get("created_at"),
                updated_at=state.get("updated_at")
            )
            for state in states
        ]
        
        logger.info(f"Retrieved {len(state_list)} states with query: {query}")
        return state_list
    
    @staticmethod
    async def get_state(db: AsyncIOMotorDatabase, state_id: str) -> Optional[StateResponse]:
        """
        获取状态详情
        """
        # 验证ObjectId
        if not ObjectId.is_valid(state_id):
            logger.warning(f"Invalid state ID format: {state_id}")
            return None
        
        state = await db.states.find_one({"_id": ObjectId(state_id)})
        if not state:
            logger.warning(f"State not found: {state_id}")
            return None
        
        state_response = StateResponse(
            id=str(state["_id"]),
            name=state["name"],
            code=state["code"],
            module_type=state["module_type"],
            description=state.get("description"),
            color=state.get("color", "#1890ff"),
            icon=state.get("icon"),
            sort_order=state.get("sort_order", 0),
            is_enabled=state.get("is_enabled", True),
            is_visible=state.get("is_visible", True),
            is_default=state.get("is_default", False),
            created_at=state.get("created_at"),
            updated_at=state.get("updated_at")
        )
        
        logger.info(f"Retrieved state: {state_id}")
        return state_response
    
    @staticmethod
    async def create_state(db: AsyncIOMotorDatabase, state_data: StateCreate) -> Optional[StateResponse]:
        """
        创建状态
        """
        # 检查代码是否已存在
        existing_state = await db.states.find_one({
            "code": state_data.code,
            "module_type": state_data.module_type
        })
        if existing_state:
            logger.warning(f"State code already exists in module {state_data.module_type}: {state_data.code}")
            return None
        
        # 如果设置为默认状态，先取消该模块其他状态的默认
        if state_data.is_default:
            await db.states.update_many(
                {
                    "module_type": state_data.module_type,
                    "is_default": True
                },
                {
                    "$set": {
                        "is_default": False,
                        "updated_at": datetime.utcnow()
                    }
                }
            )
            logger.info(f"Cleared default flags for other states in module {state_data.module_type}")
        
        # 创建状态
        now = datetime.utcnow()
        state_dict = state_data.model_dump()
        state_dict.update({
            "created_at": now,
            "updated_at": now
        })
        
        result = await db.states.insert_one(state_dict)
        
        # 返回创建的状态
        created_state = await db.states.find_one({"_id": result.inserted_id})
        
        # 清除相关缓存
        state_cache.invalidate_cache(state_data.module_type)
        
        state_response = StateResponse(
            id=str(created_state["_id"]),
            name=created_state["name"],
            code=created_state["code"],
            module_type=created_state["module_type"],
            description=created_state.get("description"),
            color=created_state.get("color", "#1890ff"),
            icon=created_state.get("icon"),
            sort_order=created_state.get("sort_order", 0),
            is_enabled=created_state.get("is_enabled", True),
            is_visible=created_state.get("is_visible", True),
            is_default=created_state.get("is_default", False),
            created_at=created_state.get("created_at"),
            updated_at=created_state.get("updated_at")
        )
        
        logger.info(f"Created state: {state_response.id}")
        return state_response
    
    @staticmethod
    async def update_state(
        db: AsyncIOMotorDatabase,
        state_id: str,
        state_data: StateUpdate
    ) -> Optional[StateResponse]:
        """
        更新状态
        """
        # 验证ObjectId
        try:
            object_id = ObjectId(state_id)
        except Exception:
            logger.warning(f"Invalid state ID format: {state_id}")
            return None
        
        # 检查状态是否存在
        existing_state = await db.states.find_one({"_id": object_id})
        if not existing_state:
            logger.warning(f"State not found: {state_id}")
            return None
        
        # 如果更新代码，检查是否与其他状态冲突
        if hasattr(state_data, 'code') and getattr(state_data, 'code') is not None:
            if state_data.code != existing_state.get("code"):
                conflict_state = await db.states.find_one({
                    "code": state_data.code,
                    "module_type": existing_state["module_type"],
                    "_id": {"$ne": object_id}
                })
                if conflict_state:
                    logger.warning(f"State code conflict in module {existing_state['module_type']}: {state_data.code}")
                    raise ValueError(f"状态代码 {state_data.code} 在模块 {existing_state['module_type']} 中已存在")
        
        # 更新状态
        # 使用model_dump(exclude_unset=True)来只获取已设置的字段
        # 但是需要过滤掉None值，只保留有值的字段
        update_dict = state_data.model_dump(exclude_unset=True)
        update_data = {}
        for k, v in update_dict.items():
            # 只包含非None值的字段（允许空字符串和False值）
            if v is not None:
                update_data[k] = v
        
        # 如果设置为默认状态，先取消该模块其他状态的默认
        if 'is_default' in update_data and update_data['is_default'] is True:
            await db.states.update_many(
                {
                    "module_type": existing_state["module_type"],
                    "is_default": True,
                    "_id": {"$ne": object_id}  # 排除当前状态
                },
                {
                    "$set": {
                        "is_default": False,
                        "updated_at": datetime.utcnow()
                    }
                }
            )
            logger.info(f"Cleared default flags for other states in module {existing_state['module_type']}")
        
        # 如果尝试禁用状态，检查该状态下是否有数据
        if 'is_enabled' in update_data and update_data['is_enabled'] is False:
            # 检查当前状态是否已启用
            if existing_state.get("is_enabled", True):
                # 检查该状态下是否有数据
                module_type = existing_state.get("module_type")
                state_code = existing_state.get("code")
                collection_name = MODULE_COLLECTION_MAP.get(module_type)
                
                if collection_name:
                    # 查询对应集合中是否有使用该状态的数据
                    # 状态代码在数据库中存储为大写，但查询时需要考虑大小写兼容性
                    state_code_upper = state_code.upper() if state_code else state_code
                    
                    # 先尝试大写格式（标准格式）
                    count = await db[collection_name].count_documents({"status": state_code_upper})
                    
                    # 如果大写格式没找到，尝试原始格式（兼容旧数据）
                    if count == 0 and state_code_upper != state_code:
                        count = await db[collection_name].count_documents({"status": state_code})
                    
                    # 也尝试大小写不敏感查询（使用正则表达式）
                    if count == 0:
                        import re
                        regex_pattern = re.compile(f"^{re.escape(state_code)}$", re.IGNORECASE)
                        count = await db[collection_name].count_documents({"status": {"$regex": regex_pattern}})
                    
                    if count > 0:
                        module_name_map = {
                            "requirement": "需求",
                            "task": "任务",
                            "defect": "缺陷",
                            "project": "项目",
                            "test_case": "测试用例",
                            "document": "文档",
                            "version": "版本"
                        }
                        module_name = module_name_map.get(module_type, module_type)
                        raise ValueError(f"无法禁用状态，该状态下存在 {count} 条{module_name}数据，请先将数据迁移到其他状态后再禁用")
        
        # 如果没有需要更新的字段，直接返回现有状态
        if not update_data:
            updated_state = await db.states.find_one({"_id": object_id})
            if not updated_state:
                logger.warning(f"State not found after update: {state_id}")
                return None
            
            state_response = StateResponse(
                id=str(updated_state["_id"]),
                name=updated_state["name"],
                code=updated_state["code"],
                module_type=updated_state["module_type"],
                description=updated_state.get("description"),
                color=updated_state.get("color", "#1890ff"),
                icon=updated_state.get("icon"),
                sort_order=updated_state.get("sort_order", 0),
                is_enabled=updated_state.get("is_enabled", True),
                is_visible=updated_state.get("is_visible", True),
                is_default=updated_state.get("is_default", False),
                created_at=updated_state.get("created_at"),
                updated_at=updated_state.get("updated_at")
            )
            return state_response
        
        update_data["updated_at"] = datetime.utcnow()
        
        result = await db.states.update_one(
            {"_id": object_id},
            {"$set": update_data}
        )
        
        if result.modified_count == 0 and result.matched_count == 0:
            logger.warning(f"State not found for update: {state_id}")
            return None
        
        # 返回更新后的状态
        updated_state = await db.states.find_one({"_id": object_id})
        if not updated_state:
            logger.error(f"Failed to retrieve updated state: {state_id}")
            return None
        
        # 清除相关缓存
        state_cache.invalidate_cache(updated_state["module_type"])
        
        state_response = StateResponse(
            id=str(updated_state["_id"]),
            name=updated_state["name"],
            code=updated_state["code"],
            module_type=updated_state["module_type"],
            description=updated_state.get("description"),
            color=updated_state.get("color", "#1890ff"),
            icon=updated_state.get("icon"),
            sort_order=updated_state.get("sort_order", 0),
            is_enabled=updated_state.get("is_enabled", True),
            is_visible=updated_state.get("is_visible", True),
            is_default=updated_state.get("is_default", False),
            created_at=updated_state.get("created_at"),
            updated_at=updated_state.get("updated_at")
        )
        
        logger.info(f"Updated state: {state_id}")
        return state_response
    
    @staticmethod
    async def delete_state(db: AsyncIOMotorDatabase, state_id: str, force: bool = False) -> Dict[str, Any]:
        """
        删除状态
        
        Args:
            db: 数据库连接
            state_id: 状态ID
            force: 是否强制删除（即使有数据也删除）
            
        Returns:
            Dict[str, Any]: 删除结果
                - success: bool - 是否成功
                - warning: Optional[str] - 警告信息（如果状态下有数据且force=False）
                - has_data: bool - 是否检测到数据
                - data_count: int - 数据数量
                - module_name: str - 模块名称
                
        Raises:
            ValueError: 如果状态不存在会抛出异常
        """
        # 验证ObjectId
        try:
            object_id = ObjectId(state_id)
        except Exception:
            logger.warning(f"Invalid state ID format: {state_id}")
            raise ValueError(f"无效的状态ID格式: {state_id}")
        
        # 检查状态是否存在
        existing_state = await db.states.find_one({"_id": object_id})
        if not existing_state:
            logger.warning(f"State not found: {state_id}")
            raise ValueError(f"状态不存在: {state_id}")
        
        # 检查该状态是否被使用（仅用于提示，不影响删除）
        module_type = existing_state.get("module_type")
        state_code = existing_state.get("code")
        state_name = existing_state.get("name", state_code)
        collection_name = MODULE_COLLECTION_MAP.get(module_type)
        has_data = False
        data_count = 0
        module_name = module_type
        
        if collection_name:
            # 查询对应集合中是否有使用该状态的数据
            # 状态代码在数据库中存储为大写，但查询时需要考虑大小写兼容性
            state_code_upper = state_code.upper() if state_code else state_code
            count = await db[collection_name].count_documents({"status": state_code_upper})
            
            # 也检查小写格式（兼容性）
            if count == 0 and state_code_upper != state_code:
                count = await db[collection_name].count_documents({"status": state_code})
            
            # 也尝试大小写不敏感查询（使用正则表达式）
            if count == 0:
                import re
                regex_pattern = re.compile(f"^{re.escape(state_code)}$", re.IGNORECASE)
                count = await db[collection_name].count_documents({"status": {"$regex": regex_pattern}})
            
            if count > 0:
                module_name_map = {
                    "requirement": "需求",
                    "task": "任务",
                    "defect": "缺陷",
                    "project": "项目",
                    "test_case": "测试用例",
                    "document": "文档"
                }
                module_name = module_name_map.get(module_type, module_type)
                has_data = True
                data_count = count
        
        # 执行删除
        result = await db.states.delete_one({"_id": object_id})
        
        if result.deleted_count == 0:
            logger.error(f"Failed to delete state: {state_id}")
            raise ValueError(f"状态删除失败: {state_id}")
        
        # 清除相关缓存
        state_cache.invalidate_cache(module_type)
        
        logger.info(f"Deleted state: {state_id}" + (f" (had {data_count} {module_name} data)" if has_data else ""))
        
        return {
            "success": True,
            "warning": f"该状态下存在 {data_count} 条{module_name}数据，已强制删除" if has_data else None,
            "has_data": has_data,
            "data_count": data_count if has_data else 0,
            "module_name": module_name if has_data else "",
            "state_name": state_name,
            "message": "状态删除成功"
        }
    
    @staticmethod
    async def batch_delete_states(db: AsyncIOMotorDatabase, state_ids: List[str], force: bool = False) -> Dict[str, Any]:
        """
        批量删除状态
        
        Args:
            db: 数据库连接
            state_ids: 状态ID列表
            force: 是否强制删除（即使有数据也删除）
            
        Returns:
            Dict[str, Any]: 包含删除结果的信息
                - deleted_count: 成功删除的数量
                - skipped_count: 跳过的数量（因为被使用或不存在）
                - errors: 错误信息列表
                - deleted_ids: 成功删除的ID列表
                - skipped_ids: 跳过的ID列表
        """
        deleted_count = 0
        skipped_count = 0
        errors = []
        deleted_ids = []
        skipped_ids = []
        
        # 验证ObjectId格式
        valid_object_ids = []
        invalid_ids = []
        for state_id in state_ids:
            if not state_id:
                continue
            try:
                valid_object_ids.append(ObjectId(state_id))
            except Exception:
                invalid_ids.append(state_id)
        
        if invalid_ids:
            errors.append(f"无效的状态ID: {', '.join(invalid_ids)}")
        
        if not valid_object_ids:
            return {
                "deleted_count": 0,
                "skipped_count": 0,
                "errors": errors,
                "deleted_ids": [],
                "skipped_ids": invalid_ids
            }
        
        # 查询所有状态
        states = await db.states.find({"_id": {"$in": valid_object_ids}}).to_list(length=None)
        state_dict = {str(state["_id"]): state for state in states}
        
        # 用于清除缓存的模块类型集合
        affected_modules = set()
        
        # 处理每个状态
        for state_id_str in state_ids:
            if not state_id_str:
                continue
            
            # 跳过无效的ID
            if state_id_str in invalid_ids:
                continue
            
            try:
                # 验证并转换ObjectId
                try:
                    object_id = ObjectId(state_id_str)
                except Exception:
                    skipped_count += 1
                    skipped_ids.append(state_id_str)
                    errors.append(f"状态ID格式无效: {state_id_str}")
                    continue
                
                # 查找状态
                existing_state = state_dict.get(state_id_str)
                
                if not existing_state:
                    skipped_count += 1
                    skipped_ids.append(state_id_str)
                    errors.append(f"状态不存在: {state_id_str}")
                    continue
                
                # 检查该状态是否被使用（仅用于提示，不影响删除）
                module_type = existing_state.get("module_type")
                state_code = existing_state.get("code")
                state_name = existing_state.get("name", state_code)
                collection_name = MODULE_COLLECTION_MAP.get(module_type)
                
                # 初始化变量
                state_has_data = False
                state_data_count = 0
                module_name = module_type  # 默认值
                
                if collection_name:
                    # 查询对应集合中是否有使用该状态的数据
                    # 状态代码在数据库中存储为大写，但查询时需要考虑大小写兼容性
                    state_code_upper = state_code.upper() if state_code else state_code
                    count = await db[collection_name].count_documents({"status": state_code_upper})
                    
                    # 也检查小写格式（兼容性）
                    if count == 0 and state_code_upper != state_code:
                        count = await db[collection_name].count_documents({"status": state_code})
                    
                    # 也尝试大小写不敏感查询（使用正则表达式）
                    if count == 0:
                        import re
                        regex_pattern = re.compile(f"^{re.escape(state_code)}$", re.IGNORECASE)
                        count = await db[collection_name].count_documents({"status": {"$regex": regex_pattern}})
                    
                    if count > 0:
                        module_name_map = {
                            "requirement": "需求",
                            "task": "任务",
                            "defect": "缺陷",
                            "project": "项目",
                            "test_case": "测试用例",
                            "document": "文档",
                            "version": "版本"
                        }
                        module_name = module_name_map.get(module_type, module_type)
                        state_has_data = True
                        state_data_count = count
                        # 记录警告信息，但不阻止删除
                        errors.append(f"状态\"{state_name}\"下存在 {count} 条{module_name}数据，已强制删除")
                
                # 删除状态
                result = await db.states.delete_one({"_id": object_id})
                
                if result.deleted_count > 0:
                    deleted_count += 1
                    deleted_ids.append(state_id_str)
                    if module_type:
                        affected_modules.add(module_type)
                    logger.info(f"Deleted state: {state_id_str} ({existing_state.get('name', '')})" + (f" (had {state_data_count} {module_name} data)" if state_has_data else ""))
                else:
                    skipped_count += 1
                    skipped_ids.append(state_id_str)
                    errors.append(f"状态\"{existing_state.get('name', state_id_str)}\"删除失败")
                    
            except ValueError as e:
                skipped_count += 1
                skipped_ids.append(state_id_str)
                errors.append(str(e))
            except Exception as e:
                skipped_count += 1
                skipped_ids.append(state_id_str)
                error_msg = str(e)
                logger.error(f"删除状态 {state_id_str} 时出错: {error_msg}")
                errors.append(f"删除状态失败: {error_msg}")
        
        # 清除所有受影响模块的缓存
        for module_type in affected_modules:
            state_cache.invalidate_cache(module_type)
        
        return {
            "deleted_count": deleted_count,
            "skipped_count": skipped_count,
            "errors": errors,
            "deleted_ids": deleted_ids,
            "skipped_ids": skipped_ids
        }
    
    @staticmethod
    async def get_module_states(
        db: AsyncIOMotorDatabase,
        module_type: str,
        force_refresh: bool = False
    ) -> List[StateResponse]:
        """
        获取指定模块的所有状态（带缓存）
        """
        # 使用缓存管理器获取状态
        states = await state_cache.get_module_states(db, module_type, force_refresh)
        logger.info(f"Retrieved states for module {module_type}, count: {len(states)}")
        return states
    
    @staticmethod
    async def init_module_states(db: AsyncIOMotorDatabase, module_type: str) -> Dict[str, Any]:
        """
        初始化模块状态（支持重复初始化，自动识别硬编码初始值的变化）
        """
        # 根据模块类型定义默认状态
        default_states = {
            "project": [
                {"name": "新建", "code": "new", "color": "#d9d9d9", "sort_order": 1, "is_default": True, "description": "项目新建"},
                {"name": "规划中", "code": "planning", "color": "#d9d9d9", "sort_order": 2, "description": "项目正在规划阶段"},
                {"name": "进行中", "code": "active", "color": "#1890ff", "sort_order": 3, "description": "项目正在执行中"},
                {"name": "暂停", "code": "on_hold", "color": "#faad14", "sort_order": 4, "description": "项目暂时暂停"},
                {"name": "已完成", "code": "completed", "color": "#52c41a", "sort_order": 5, "description": "项目已完成"},
                {"name": "已取消", "code": "cancelled", "color": "#ff4d4f", "sort_order": 6, "description": "项目已取消"},
                {"name": "已归档", "code": "archived", "color": "#8c8c8c", "sort_order": 7, "description": "项目已归档"}
            ],
            "requirement": [
                {"name": "草稿", "code": "draft", "color": "#94a3b8", "sort_order": 0, "is_default": True, "description": "需求草稿"},
                {"name": "新建", "code": "new", "color": "#d9d9d9", "sort_order": 1, "description": "需求新建"},
                {"name": "待分配", "code": "open", "color": "#1890ff", "sort_order": 2, "description": "需求待分配"},
                {"name": "已分配", "code": "assigned", "color": "#1890ff", "sort_order": 3, "description": "需求已分配"},
                {"name": "待分析", "code": "pending_analysis", "color": "#faad14", "sort_order": 4, "description": "需求待分析"},
                {"name": "已分析", "code": "analyzed", "color": "#1890ff", "sort_order": 5, "description": "需求已分析"},
                {"name": "进行中", "code": "in_progress", "color": "#1890ff", "sort_order": 6, "description": "需求进行中"},
                {"name": "已完成", "code": "done", "color": "#52c41a", "sort_order": 7, "description": "需求已完成"},
                {"name": "已取消", "code": "cancelled", "color": "#ff4d4f", "sort_order": 8, "description": "需求已取消"},
                {"name": "已归档", "code": "archived", "color": "#8c8c8c", "sort_order": 9, "description": "需求已归档"}
            ],
            "task": [
                {"name": "新建", "code": "new", "color": "#d9d9d9", "sort_order": 1, "is_default": True, "description": "任务新建"},
                {"name": "已分配", "code": "assigned", "color": "#1890ff", "sort_order": 2, "description": "任务已分配"},
                {"name": "进行中", "code": "in_progress", "color": "#faad14", "sort_order": 3, "description": "任务进行中"},
                {"name": "已完成", "code": "done", "color": "#52c41a", "sort_order": 4, "description": "任务已完成"},
                {"name": "已取消", "code": "cancelled", "color": "#ff4d4f", "sort_order": 5, "description": "任务已取消"}
            ],
            "defect": [
                {"name": "新建", "code": "new", "color": "#d9d9d9", "sort_order": 1, "is_default": True, "description": "缺陷新建"},
                {"name": "已分配", "code": "assigned", "color": "#1890ff", "sort_order": 2, "description": "缺陷已分配"},
                {"name": "进行中", "code": "in_progress", "color": "#faad14", "sort_order": 3, "description": "缺陷进行中"},
                {"name": "已解决", "code": "resolved", "color": "#52c41a", "sort_order": 4, "description": "缺陷已解决"},
                {"name": "已验证", "code": "verified", "color": "#8c8c8c", "sort_order": 5, "description": "缺陷已验证"},
                {"name": "已关闭", "code": "closed", "color": "#8c8c8c", "sort_order": 6, "description": "缺陷已关闭"},
                {"name": "重新打开", "code": "reopened", "color": "#8c8c8c", "sort_order": 7, "description": "缺陷重新打开"}
            ],
            "version": [
                {"name": "草稿", "code": "draft", "color": "#d9d9d9", "sort_order": 1, "is_default": True, "description": "版本草稿"},
                {"name": "规划中", "code": "planning", "color": "#d9d9d9", "sort_order": 2, "description": "版本规划中"},
                {"name": "开发中", "code": "development", "color": "#1890ff", "sort_order": 3, "description": "版本开发中"},
                {"name": "测试中", "code": "testing", "color": "#faad14", "sort_order": 4, "description": "版本测试中"},
                {"name": "预发布", "code": "pre_release", "color": "#722ed1", "sort_order": 5, "description": "版本预发布"},
                {"name": "已发布", "code": "released", "color": "#52c41a", "sort_order": 6, "description": "版本已发布"},
                {"name": "已废弃", "code": "deprecated", "color": "#ff4d4f", "sort_order": 7, "description": "版本已废弃"},
                {"name": "已归档", "code": "archived", "color": "#8c8c8c", "sort_order": 8, "description": "版本已归档"}
            ],
            "document": [
                {"name": "新建", "code": "new", "color": "#d9d9d9", "sort_order": 1, "is_default": True, "description": "文档新建"},
                {"name": "待审核", "code": "pending_review", "color": "#faad14", "sort_order": 2, "description": "文档待审核"},
                {"name": "已发布", "code": "published", "color": "#52c41a", "sort_order": 3, "description": "文档已发布"},
                {"name": "已过期", "code": "expired", "color": "#ff4d4f", "sort_order": 4, "description": "文档已过期"},
                {"name": "已归档", "code": "archived", "color": "#8c8c8c", "sort_order": 5, "description": "文档已归档"}
            ],
            "user": [
                {"name": "待激活", "code": "pending", "color": "#d9d9d9", "sort_order": 1, "is_default": True, "description": "用户待激活"},
                {"name": "已激活", "code": "active", "color": "#52c41a", "sort_order": 2, "description": "用户已激活"},
                {"name": "已禁用", "code": "disabled", "color": "#ff4d4f", "sort_order": 3, "description": "用户已禁用"},
                {"name": "已锁定", "code": "locked", "color": "#faad14", "sort_order": 4, "description": "用户已锁定"},
                {"name": "已注销", "code": "deleted", "color": "#8c8c8c", "sort_order": 5, "description": "用户已注销"}
            ],
            "comment": [
                {"name": "待审核", "code": "pending", "color": "#d9d9d9", "sort_order": 1, "is_default": True, "description": "评论待审核"},
                {"name": "已发布", "code": "published", "color": "#52c41a", "sort_order": 2, "description": "评论已发布"},
                {"name": "已隐藏", "code": "hidden", "color": "#faad14", "sort_order": 3, "description": "评论已隐藏"},
                {"name": "已删除", "code": "deleted", "color": "#ff4d4f", "sort_order": 4, "description": "评论已删除"}
            ],
            "notification": [
                {"name": "未读", "code": "unread", "color": "#1890ff", "sort_order": 1, "is_default": True, "description": "通知未读"},
                {"name": "已读", "code": "read", "color": "#52c41a", "sort_order": 2, "description": "通知已读"},
                {"name": "已删除", "code": "deleted", "color": "#ff4d4f", "sort_order": 3, "description": "通知已删除"}
            ],
            "test_case": [
                {"name": "设计中", "code": "design", "color": "#d9d9d9", "sort_order": 1, "is_default": True, "description": "测试用例设计中"},
                {"name": "就绪", "code": "ready", "color": "#1890ff", "sort_order": 2, "description": "测试用例就绪，可以执行"},
                {"name": "执行中", "code": "executing", "color": "#faad14", "sort_order": 3, "description": "测试用例执行中"},
                {"name": "通过", "code": "passed", "color": "#52c41a", "sort_order": 4, "description": "测试用例执行通过"},
                {"name": "失败", "code": "failed", "color": "#ff4d4f", "sort_order": 5, "description": "测试用例执行失败"},
                {"name": "阻塞", "code": "blocked", "color": "#fa8c16", "sort_order": 6, "description": "测试用例被阻塞"},
                {"name": "跳过", "code": "skipped", "color": "#8c8c8c", "sort_order": 7, "description": "测试用例被跳过"},
                {"name": "已废弃", "code": "deprecated", "color": "#8c8c8c", "sort_order": 8, "description": "测试用例已废弃"}
            ],
            "test_plan": [
                {"name": "待执行", "code": "pending", "color": "#d9d9d9", "sort_order": 1, "is_default": True, "description": "测试计划待执行"},
                {"name": "执行中", "code": "executing", "color": "#faad14", "sort_order": 2, "description": "测试计划执行中"},
                {"name": "已完成", "code": "completed", "color": "#52c41a", "sort_order": 3, "description": "测试计划已完成"}
            ],
            "approval": [
                {"name": "待审批", "code": "pending", "color": "#faad14", "sort_order": 1, "is_default": True, "description": "审批申请已提交，等待审批"},
                {"name": "审批中", "code": "in_progress", "color": "#1890ff", "sort_order": 2, "description": "审批正在进行中"},
                {"name": "已通过", "code": "approved", "color": "#52c41a", "sort_order": 3, "description": "审批已通过"},
                {"name": "已拒绝", "code": "rejected", "color": "#ff4d4f", "sort_order": 4, "description": "审批已拒绝"},
                {"name": "已取消", "code": "cancelled", "color": "#8c8c8c", "sort_order": 5, "description": "审批申请已取消"}
            ]
        }
        
        # 获取对应模块的默认状态
        states_to_sync = default_states.get(module_type, [])
        if not states_to_sync:
            logger.warning(f"Unsupported module type: {module_type}")
            raise ValueError(f"Unsupported module type: {module_type}")
        
        # 获取数据库中已存在的状态（通过 code 和 module_type 匹配）
        existing_states_cursor = db.states.find({"module_type": module_type})
        existing_states = await existing_states_cursor.to_list(length=None)
        existing_states_dict = {state["code"]: state for state in existing_states}
        
        now = datetime.utcnow()
        created_states = []
        updated_states = []
        
        # 处理每个硬编码状态
        for state_data in states_to_sync:
            state_code = state_data["code"]
            existing_state = existing_states_dict.get(state_code)
            
            # 准备状态数据
            state_dict = {
                "name": state_data["name"],
                "code": state_code,
                "module_type": module_type,
                "color": state_data["color"],
                "sort_order": state_data["sort_order"],
                "description": state_data.get("description"),
                "is_enabled": True,
                "is_visible": True,
                "is_default": state_data.get("is_default", False),
            }
            
            if existing_state:
                # 完全覆盖硬编码字段（点击初始化就是覆盖，不是判断是否需要更新）
                # 强制覆盖所有硬编码字段，包括 sort_order、name、color、description、is_default 等
                update_fields = {
                    "name": state_dict["name"],
                    "color": state_dict["color"],
                    "sort_order": state_dict["sort_order"],  # 强制覆盖排序顺序
                    "description": state_dict.get("description"),
                    "is_default": state_dict["is_default"],
                    "is_enabled": state_dict["is_enabled"],  # 强制启用
                    "is_visible": state_dict["is_visible"],  # 强制可见
                    "updated_at": now
                }
                
                # 执行更新（完全覆盖）
                await db.states.update_one(
                    {"_id": existing_state["_id"]},
                    {"$set": update_fields}
                )
                
                # 获取更新后的状态
                updated_state = await db.states.find_one({"_id": existing_state["_id"]})
                
                state_response = StateResponse(
                    id=str(updated_state["_id"]),
                    name=updated_state["name"],
                    code=updated_state["code"],
                    module_type=updated_state["module_type"],
                    description=updated_state.get("description"),
                    color=updated_state.get("color", "#1890ff"),
                    icon=updated_state.get("icon"),  # 保留用户自定义的图标
                    sort_order=updated_state.get("sort_order", 0),
                    is_enabled=updated_state.get("is_enabled", True),
                    is_visible=updated_state.get("is_visible", True),
                    is_default=updated_state.get("is_default", False),
                    created_at=updated_state.get("created_at"),
                    updated_at=updated_state.get("updated_at")
                )
                updated_states.append(state_response)
                logger.info(f"Overridden state {state_code} for module {module_type} with hardcoded values")
            else:
                # 创建新状态
                state_dict.update({
                    "created_at": now,
                    "updated_at": now
                })
                
                result = await db.states.insert_one(state_dict)
                created_state = await db.states.find_one({"_id": result.inserted_id})
                
                state_response = StateResponse(
                    id=str(created_state["_id"]),
                    name=created_state["name"],
                    code=created_state["code"],
                    module_type=created_state["module_type"],
                    description=created_state.get("description"),
                    color=created_state.get("color", "#1890ff"),
                    icon=created_state.get("icon"),
                    sort_order=created_state.get("sort_order", 0),
                    is_enabled=created_state.get("is_enabled", True),
                    is_visible=created_state.get("is_visible", True),
                    is_default=created_state.get("is_default", False),
                    created_at=created_state.get("created_at"),
                    updated_at=created_state.get("updated_at")
                )
                created_states.append(state_response)
                logger.info(f"Created state {state_code} for module {module_type}")
        
        # 处理数据库中存在但硬编码中不存在的状态（标记为禁用和不可见）
        # 获取硬编码状态的所有code
        hardcoded_codes = {state["code"] for state in states_to_sync}
        
        # 查找数据库中存在但不在硬编码中的状态
        states_to_disable = []
        for existing_code, existing_state in existing_states_dict.items():
            if existing_code not in hardcoded_codes:
                # 标记为禁用和不可见（但不删除，保留历史数据）
                await db.states.update_one(
                    {"_id": existing_state["_id"]},
                    {
                        "$set": {
                            "is_enabled": False,
                            "is_visible": False,
                            "updated_at": now
                        }
                    }
                )
                states_to_disable.append(existing_code)
                logger.info(f"Disabled state {existing_code} in module {module_type}")
        
        # 清除相关缓存
        state_cache.invalidate_cache(module_type)
        
        return {
            "created": created_states,
            "updated": updated_states,
            "disabled": states_to_disable,
            "created_count": len(created_states),
            "updated_count": len(updated_states),
            "disabled_count": len(states_to_disable)
        }
    
    @staticmethod
    async def get_module_state_options(db: AsyncIOMotorDatabase, module_type: str) -> List[Dict[str, Any]]:
        """
        获取模块状态选项（用于前端下拉框）
        """
        options = await state_cache.get_state_options(db, module_type)
        logger.info(f"Retrieved state options for module {module_type}")
        return options
    
    @staticmethod
    async def validate_state_code(db: AsyncIOMotorDatabase, module_type: str, code: str) -> bool:
        """
        验证状态代码是否有效
        """
        is_valid = await state_cache.validate_state_code(db, module_type, code)
        logger.info(f"Validated state code {code} for module {module_type}: {is_valid}")
        return is_valid
    
    @staticmethod
    async def get_default_state(db: AsyncIOMotorDatabase, module_type: str) -> Optional[Dict[str, Any]]:
        """
        获取模块默认状态
        """
        default_state = await state_cache.get_default_state(db, module_type)
        if default_state:
            logger.info(f"Retrieved default state for module {module_type}")
        else:
            logger.warning(f"No default state found for module {module_type}")
        return default_state
    
    @staticmethod
    async def generate_typescript_types(db: AsyncIOMotorDatabase) -> str:
        """
        生成TypeScript类型定义
        """
        types_content = await state_cache.generate_typescript_types(db)
        logger.info("Generated TypeScript types for states")
        return types_content
    
    @staticmethod
    def invalidate_cache(module_type: Optional[str] = None):
        """
        清除状态缓存
        """
        state_cache.invalidate_cache(module_type)
        if module_type:
            logger.info(f"Invalidated cache for module {module_type}")
        else:
            logger.info("Invalidated all state caches")
